﻿namespace AddressBook.Business.Person
{
	#region "Using Statements"
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Text;
  using System.Text.RegularExpressions;

	using Csla;
	using Csla.Data;
	#endregion

	[Serializable]
	public class PhoneNumber
	{
		#region "Factory Methods"

    private static string sRegexPhonePattern = "^(?<long>1)?[-| ]?(\\({0,1}(?<area>\\d{3})\\){0,1})[-| ]?(?<phone1>\\d{3})[-| ]?(?<phone2>\\d{4})\\z";
    private static string sRegexFormatPhone = "(${area}) ${phone1}-${phone2}";
    private static string sRegexUnFormatPhone = "${area}${phone1}${phone2}";

    public static string FormatPhone(string phoneNumber)
    {
      return Regex.Replace(phoneNumber, sRegexPhonePattern, sRegexFormatPhone);
    }

    public static string UnFormatPhone(string phoneNumber)
    {
      return Regex.Replace(phoneNumber, sRegexPhonePattern, sRegexUnFormatPhone);
    }

    public static bool IsValidPhone(string phoneNumber)
    {
      if (phoneNumber.Length >= 10 && phoneNumber.Length <= 14)
        return Regex.IsMatch(phoneNumber, sRegexPhonePattern);
      else
        return false;
    }

		private PhoneNumber()
		{ /*require use of factory methods*/ }

		#endregion

		#region "Data Access"

		public static Int32 AddPhoneNumber(string phoneNumber)
		{
			int phoneNumberId;

			using (var ctx = ContextManager<AddressBook.Business.Model.AddressBookDataContext>.GetManager(AddressBook.Business.Model.Database.AddressBook))
			{
				AddressBook.Business.Model.PhoneNumber phone = new AddressBook.Business.Model.PhoneNumber();

				phone.PhoneNumber1 = UnFormatPhone(phoneNumber);
				phone.ModifiedDate = System.DateTime.Now;

				ctx.DataContext.PhoneNumbers.InsertOnSubmit(phone);
				ctx.DataContext.SubmitChanges();

				phoneNumberId = phone.Id;
			}

			return phoneNumberId;
		}

		public static void UpdatePhoneNumber(Int32 id, string phoneNumber)
		{
			using (var ctx = ContextManager<AddressBook.Business.Model.AddressBookDataContext>.GetManager(AddressBook.Business.Model.Database.AddressBook))
			{
				AddressBook.Business.Model.PhoneNumber phone = ctx.DataContext.PhoneNumbers.First(p => p.Id == id);

				phone.PhoneNumber1 = UnFormatPhone(phoneNumber);
				phone.ModifiedDate = System.DateTime.Now;

				ctx.DataContext.SubmitChanges();
			}
		}

		public static void RemovePhoneNumber(Int32 id)
		{
			using (var ctx = ContextManager<AddressBook.Business.Model.AddressBookDataContext>.GetManager(AddressBook.Business.Model.Database.AddressBook))
			{
				AddressBook.Business.Model.PhoneNumber phone = ctx.DataContext.PhoneNumbers.First(p => p.Id == id);

				ctx.DataContext.PhoneNumbers.DeleteOnSubmit(phone);
				ctx.DataContext.SubmitChanges();
			}
		}
	
		#endregion
	}
}
